﻿Ext.define('SmartClient.controller.AddedProductsController',
   {
      extend: 'Deft.mvc.ViewController',
      inject: ['productsStore'],

      init: function ()
      {
         // Remove item action
         this.getActionColumn().items[0].handler = this.removeItem;
         this.getConfirmButton().setHandler(this.confirmOrder, this);
         this.getCancelButton().setHandler(this.cancel, this.getView());
         this.getView().down('gridpanel').addListener('resize', SmartClient.utils.CommonFunctions.setWindowSizeAndPosition,
            this.getView(), 'addedProductsWindow');
         var cellEditingPlugin = this.getView().items.items[0].plugins[0];
         cellEditingPlugin.addListener('beforeedit', this.setEditingFieldStep);
         cellEditingPlugin.addListener('edit', this.validateEditingValue, cellEditingPlugin, this.getProductsStore());
         if (this.getView().orderId)
         {
            // Show this button when in order edit mode
            this.getAddItemsButton().show();
            this.getAddItemsButton().addListener('click', this.addItems, this.getView());
         }
         return this.callParent(arguments);
      },

      // Element IDs here
      // DeftJS will create a getter and setter for property
      control:
         {
            actionColumn: true,
            confirmButton: true,
            cancelButton: true,
            addItemsButton: true
         },

      // Ext JS will create a getter and setter for property
      config:
         {
            productsStore: null
         },
   
      removeItem: function (grid, rowNum, colNum)
      {
         var productsController = Ext.getCmp('productsPanel').getController(),
             itemId = grid.getStore().getAt(rowNum).get('id'),
             cookieValue = SmartClient.utils.CookieUtils.getCookieValue(productsController.self.ADDED_PRODUCTS_COOKIE),
             addedProduct = productsController.findAddedProduct(itemId)[0],
             addedProductAfterDelimiter = new RegExp('\\'
                  + productsController.self.ADDED_PRODUCTS_DELIMITER + addedProduct),
             newCookieValue;

         if (addedProductAfterDelimiter.test(cookieValue))
         {
            newCookieValue = cookieValue.replace(addedProductAfterDelimiter, '');
         }
         else
         {
            newCookieValue = cookieValue.replace(new RegExp(addedProduct + '\\'
               + productsController.self.ADDED_PRODUCTS_DELIMITER + '?'), '');
         }
         SmartClient.utils.CookieUtils.setCookie(productsController.self.ADDED_PRODUCTS_COOKIE, newCookieValue, 30);
         grid.getStore().removeAt(rowNum);
         productsController.refreshViewAddedProductsButtonText();

         if (grid.getStore().getCount() == 0)
         {
            setTimeout(function ()
            {
               Ext.getCmp('addedProductsWindow').destroy();
            }, 10);
         }
      },

      confirmOrder: function ()
      {
         var addedProductsStore = Ext.getCmp('addedProductsGrid').getStore(),
             products = [];
             customer =
             {
                id: SmartClient.utils.CookieUtils.getCookieValue(SmartClient.Application.USER_COOKIE),
                orders:
                   [
                      {
                         id: SmartClient.utils.CookieUtils.getCookieValue(SmartClient.Application.EDITED_ORDER_COOKIE),
                         products: products
                      }
                   ]
             };
         addedProductsStore.each(function (addedProductModel)
         {
            products.push(
               {
                  id: addedProductModel.get('id'),
                  orderedAmount: addedProductModel.get('orderedAmount')
               });
         });

         var me = this;
         Ext.Ajax.request(
            {
               url: 'confirmOrder',
               method: 'POST',
               headers: { 'Content-Type': 'application/json' },
               params: Ext.JSON.encode(customer),
               success: function (conn, response, options, eOpts)
               {
                  addedProductsStore.removeAll();
                  me.getView().close();
                  me.eraseCookiesAndRefreshViewAddedProductsButtonText(true); // Reload products - true
               },
               failure: function (conn, response, options, eOpts)
               {
                  addedProductsStore.removeAll();
                  me.getView().close();
                  me.eraseCookiesAndRefreshViewAddedProductsButtonText(true); // Reload products - true
               }
            });
      },

      cancel: function()
      {
         var view = this;

         view.close();
         if (view.orderId)
         {
            // If in order edit mode
            view.getController().eraseCookiesAndRefreshViewAddedProductsButtonText();
         }
      },

      setEditingFieldStep: function (editor, context, eOpts)
      {
         var units = context.record.data['units'];
         if (units === SmartClient.controller.ProductsController.PCS_UNITS)
         {
            context.column.field.step = 1;
         }
      },

      validateEditingValue: function (editor, context, productsStore)
      {
         var amount = context.value;

         if (context.value <= 0)
         {
            amount = 1;
         }
         var availableAmount = productsStore.getById(context.record.data['id']).data.availableAmount;
         if (context.value > availableAmount)
         {
            amount = availableAmount;
         }
         context.record.set('orderedAmount', amount);

         var productId = productsStore.getById(context.record.data['id']).data.id,
             productsController = Ext.getCmp('productsPanel').getController();
         productsController.updateProductAmount(productId, amount);
      },

      addItems: function ()
      {
         this.close();
      },

      // Erases cookies and refreshes button text in ProductsView
      eraseCookiesAndRefreshViewAddedProductsButtonText: function (reloadProducts)
      {
         SmartClient.utils.CookieUtils.eraseCookie(SmartClient.Application.EDITED_ORDER_COOKIE);
         SmartClient.utils.CookieUtils.eraseCookie(SmartClient.Application.ADDED_PRODUCTS_COOKIE);
         var productsController = Ext.getCmp('productsPanel').getController();
         productsController.refreshViewAddedProductsButtonText();
         if (reloadProducts)
         {
            productsController.getProductsStore().removeAll();
            productsController.getProductsList().update([]);
            // ProductsController has event on load data that updates products list
            productsController.getProductsStore().load();
         }
      }
   });